// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'
/*import iView from 'view-design'*/
/*import viewDesign from 'view-design'*/
import ViewUI from 'view-design';
import i18n from '@/locale'

import importDirective from '@/directive'
import { directive as clickOutside } from 'v-click-outside-x'
import installPlugin from '@/plugin'
//import './my-theme/index.less'
import '@/assets/icons/iconfont.css'
import '@/assets/fonts/menu/iconfont.css'
import '@/assets/fonts/menu/iconfont.js'
import VOrgTree from 'v-org-tree'
import 'v-org-tree/dist/v-org-tree.css'
import VedioPlayer from '@/components/vedioplayer/VediojsPlayer.vue'
import BaiduMap from 'vue-baidu-map'
import './index.less';
import dataV from '@jiaminghi/data-view';
import QRCode from 'qrcode';
import Fingerprint2 from 'fingerprintjs2';
//import config from './public/config.js'
import config from '@/config'
import videojs from 'video.js'
import moment from 'moment'
import {TOKEN_KEY} from "@/libs/util";
import login from "@/api/login";
/*import elemenui from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css';
Vue.use(elemenui)*/
Vue.prototype.$videoJS = videojs;
Vue.prototype.$moment = moment;

//Vue.commandLine.appendSwitch("--ignore-certificate-errors", "true");

// 生成浏览器唯一ID，同一台电脑的ID是相同的
// 改了，改成一个窗口产生一个UUID
Fingerprint2.get(function(components) {
  const values = components.map(function(component,index) {
    if (index === 0) { //把微信浏览器里UA的wifi或4G等网络替换成空,不然切换网络会ID不一样
      return component.value.replace(/\bNetType\/\w+\b/, '');
    }
    return component.value;
  })
  //console.log(values)  //使用的浏览器信息npm
  // 生成最终id
  let port = window.location.port;
  //console.log(port);
  //const fingerPrint = Fingerprint2.x64hash128(values.join(port), 31)
  const fingerPrint = getUuid(32,109)
  Vue.prototype.$browserId = fingerPrint;
  console.log("唯一标识码(现在是UUID，一个窗口生成一个)：" + fingerPrint);

  const originBrowseId = sessionStorage.getItem("browse_id")
  console.log(">>>>>> main.oldId: %o",originBrowseId);
  if (!!originBrowseId){
    sse(originBrowseId);
  }else{
    sse(fingerPrint);
  }





  /*  let d = new Date().getTime(); //Timestamp
  let d2 = (performance && performance.now && (performance.now()*1000)) || 0; //Time in microseconds since page-load or 0 if unsupported
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
      var r = Math.random() * 16; //random number between 0 and 16
      if(d > 0) { //Use timestamp until depleted
        r = (d + r)%16 | 0;
        d = Math.floor(d/16);
      } else { //Use microseconds since page-load if supported
        r = (d2 + r)%16 | 0;
        d2 = Math.floor(d2/16);
      }
      return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
  }

  console.log(generateUUID()); // 输出类似于 "9fd9a3e8-ae6f-490d-8a8e-6e5d34faef69" 的UUID*/
});




/*import TreeTable from 'tree-table-vue'*/

// 实际打包时应该不引入mock
/* eslint-disable */
if (process.env.NODE_ENV !== 'production') require('@/mock')

/*Vue.use(iView, {
  i18n: (key, value) => i18n.t(key, value)
})*/
Vue.use(ViewUI,{i18n: (key, value) => i18n.t(key, value)})
Vue.use(QRCode)
/*Vue.use(TreeTable)*/
Vue.use(VOrgTree)
Vue.component("VedioPlayer", VedioPlayer);//全局自定义组件
/** 百度地图 */
Vue.use(BaiduMap, {
  // ak 是在百度地图开发者平台申请的密钥 详见 http://lbsyun.baidu.com/apiconsole/key */
  ak: 'IfkNE0XDdoaTwdGGkOWrALDkFZOTI9b8'});//全局自定义组件
/**
 * @description 注册admin内置插件
 */
Vue.use(dataV);
installPlugin(Vue)
/**
 * 浏览器音视频解码支持，针对jessibuca-pro
 */
checkBrowseDecoded();
/**
 * @description 生产环境关掉提示
 */
Vue.config.productionTip = false
/**
 * @description 全局注册应用配置
 */
Vue.prototype.$config = config
/**
 * 注册指令
 */
importDirective(Vue);
Vue.directive('clickOutside', clickOutside)



/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  i18n,
  store,
  render: h => h(App)
})

function checkBrowseDecoded(){
  //支持MSE H264解码；
  Vue.prototype.$supportMseH264 = window.MediaSource && window.MediaSource.isTypeSupported('video/mp4; codecs="avc1.64002A"');
  //支持MSE H265解码
  Vue.prototype.$supportMseHevc = window.MediaSource && window.MediaSource.isTypeSupported('video/mp4; codecs="hev1.1.6.L123.b0"');
  //支持Webcodecs H264解码(https/localhost)
  Vue.prototype.$supportWcs = "VideoEncoder" in window;
  //支持Webcodecs H265解码(https/localhost),会自动切换成wasm解码
  const browserInfo = getBrowser();
  Vue.prototype.$supportWcsHevc = browserInfo.type.toLowerCase() === 'chrome' && browserInfo.version >= 107 && (location.protocol === 'https:' || location.hostname === 'localhost');
  //支持WASM解码
  let supportWasm=false;
  try {
    if (typeof window.WebAssembly === 'object' && typeof window.WebAssembly.instantiate === 'function') {
      const module = new window.WebAssembly.Module(Uint8Array.of(0x0, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00));
      if (module instanceof window.WebAssembly.Module) {
        supportWasm =  new window.WebAssembly.Instance(module) instanceof window.WebAssembly.Instance;
      }
    }
  } catch (e) {
    console.log(">>>>> supportWASM: %o",e)
  }
  Vue.prototype.$supportWasm = supportWasm;
  //支持WASM SIMD解码
  Vue.prototype.$supportSimd = WebAssembly && WebAssembly.validate(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 5, 1, 96, 0, 1, 123, 3, 2, 1, 0, 10, 10, 1, 8, 0, 65, 0, 253, 15, 253, 98, 11]));
  //支持WASM WASM(SIMD) 多线程解码
  let supportMtSimd = false;
  try {
    new SharedArrayBuffer(1);
    supportMtSimd=true;
  } catch (e) {
    console.log(">>>>> supportMtSimd: %o",e)
  }
  Vue.prototype.$supportMtSimd = supportMtSimd;
}

//取浏览器属性
function getBrowser() {
  const UserAgent = window.navigator.userAgent.toLowerCase() || '';
  let browserInfo = {
    type: '',
    version: ''
  };
  let browserArray = {
    IE: window.ActiveXObject || "ActiveXObject" in window, // IE
    Chrome: UserAgent.indexOf('chrome') > -1 && UserAgent.indexOf('safari') > -1, // Chrome浏览器
    Firefox: UserAgent.indexOf('firefox') > -1, // 火狐浏览器
    Opera: UserAgent.indexOf('opera') > -1, // Opera浏览器
    Safari: UserAgent.indexOf('safari') > -1 && UserAgent.indexOf('chrome') == -1, // safari浏览器
    Edge: UserAgent.indexOf('edge') > -1, // Edge浏览器
    QQBrowser: /qqbrowser/.test(UserAgent), // qq浏览器
    WeixinBrowser: /MicroMessenger/i.test(UserAgent) // 微信浏览器
  };
  // console.log(browserArray)
  for (let i in browserArray) {
    if (browserArray[i]) {
      let versions = '';
      if (i === 'IE') {
        const versionArray = UserAgent.match(/(msie\s|trident.*rv:)([\w.]+)/)
        if (versionArray && versionArray.length > 2) {
          versions = UserAgent.match(/(msie\s|trident.*rv:)([\w.]+)/)[2];
        }
      } else if (i === 'Chrome') {
        for (let mt in navigator.mimeTypes) {
          //检测是否是360浏览器(测试只有pc端的360才起作用)
          if (navigator.mimeTypes[mt]['type'] === 'application/360softmgrplugin') {
            i = '360';
          }
        }
        const versionArray = UserAgent.match(/chrome\/([\d.]+)/);
        if (versionArray && versionArray.length > 1) {
          versions = versionArray[1];
        }
      } else if (i === 'Firefox') {
        const versionArray = UserAgent.match(/firefox\/([\d.]+)/);
        if (versionArray && versionArray.length > 1) {
          versions = versionArray[1];
        }
      } else if (i === 'Opera') {
        const versionArray = UserAgent.match(/opera\/([\d.]+)/);
        if (versionArray && versionArray.length > 1) {
          versions = versionArray[1];
        }
      } else if (i === 'Safari') {
        const versionArray = UserAgent.match(/version\/([\d.]+)/);
        if (versionArray && versionArray.length > 1) {
          versions = versionArray[1];
        }
      } else if (i === 'Edge') {
        const versionArray = UserAgent.match(/edge\/([\d.]+)/);
        if (versionArray && versionArray.length > 1) {
          versions = versionArray[1];
        }
      } else if (i === 'QQBrowser') {
        const versionArray = UserAgent.match(/qqbrowser\/([\d.]+)/);
        if (versionArray && versionArray.length > 1) {
          versions = versionArray[1];
        }
      }
      browserInfo.type = i;
      browserInfo.version = parseInt(versions);
    }
  }
  return browserInfo;
}

/**
 * 取UUID
 * @param len  长度，
 * @param radix 基数
 * @returns {string}
 */
function getUuid(len, radix) {
  const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  let uuid = [], i;
  //radix = radix || chars.length;
  radix = radix>chars.length?chars.length:radix;
  //console.log(radix);
  if (len) {
    // Compact form
    for (i = 0; i < len; i++) {
      //console.log(0 | Math.random() * radix);
      uuid[i] = chars[0 | Math.random() * radix];
    }
  } else {
    // rfc4122, version 4 form
    let r;
    // rfc4122 requires these characters
    uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
    uuid[14] = '4';

    // Fill in random data.  At i==19 set the high bits of clock sequence as
    // per rfc4122, sec. 4.1.5
    for (i = 0; i < 36; i++) {
      if (!uuid[i]) {
        r = 0 | Math.random() * 16;
        uuid[i] = chars[(i === 19) ? (r & 0x3) | 0x8 : r];
      }
    }
  }
  return uuid.join('');
}

function sse(browserId){
  console.log(">>>>>> main->store:%o",store)
  store.commit("setDeviceStatus",{deviceCode:'123456',status:0})
  //store.state.login.setDeviceStatus({deviceCode:'123456',status:0});
  const token = sessionStorage.getItem("token");
  console.log(">>>>>> main->token:%o",token)
  let baseUrl = process.env.NODE_ENV === 'development' ? config.sseUrl.dev() : config.sseUrl.pro()
  if (baseUrl[baseUrl.length-1] !== "/") baseUrl = baseUrl + "/";
  const eventSource = new EventSource(baseUrl+'sse/emit?clientId=' + browserId + "&token="+token);
  if (!!eventSource){
    eventSource.removeEventListener('open', null);
    eventSource.removeEventListener('message', null);
    eventSource.removeEventListener('error', null);
  }
  eventSource.addEventListener('message', function(evt) {
    console.log("SSE 收到信息：%o",evt.data);
    const data = JSON.parse(evt.data);
    if (data.code === 0){
      if (data.data != null){
        if (data.data.type === 'ALARM_NOTIFY'){
          //报警数据
          store.commit("pushUserMessage",data.data.object)
          //that.pushUserMessage(data.data);
        }else if (data.data.type === 'UP_DOWN_LINE_NOTIFY'){
          console.log("保存设备上下线状态信息：%o", data.data.object)
          //设备上下线
          store.commit("setDeviceStatus",data.data.object)
          //that.setDeviceStatus(data.data.object)
        }else if (data.data.type === 'MEDIA_REPLAY_FINISHED'){
          console.log("保存录像回放结束信息：%o", data.data.object)
          //回放结束
          store.commit("setMediaReplayFinish",data.data.object)
          //that.setMediaReplayFinish(data.data.object)
        }else if (data.data.type === 'MEDIA_DOWNLOAD_FINISHED'){
          console.log("保存录像下载结束信息：%o", data.data.object)
          //录像结束
        }
      }
    }else{
      console.error("%o",data.data.object)
    }
  });
  /** open 事件 */
  eventSource.addEventListener('open', function(e) {
    console.info("SSE连接打开.");
  }, false);
  /** error 事件 */
  eventSource.addEventListener('error', function(e) {
    if (e.target.readyState == EventSource.CLOSED) {
      console.error("SSE连接关闭, n秒后重连...... ");
    } else {
      console.error("SSE 错误：%o",e.target.readyState);
    }
  }, false);
  sessionStorage.setItem("browse_id",browserId);
}

